package com.wenhai.spring.dependency.lookup;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @Author:wenhai
 * @Description: 层次性依赖查找
 * @Date:2020/3/25
 */
public class HierarchicalDependencyLookupDemo {
    private static String str;
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(HierarchicalDependencyLookupDemo.class);
        // 获取HierarchicalBeanFactory<---ConfigurableBeanFactory<--ConfigurableListableBeanFactory
        ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
        System.out.println("当前 BeanFactory的 ParentFactory ：" + beanFactory.getParentBeanFactory());
        // 设置ParentBeanFactory
        HierarchicalBeanFactory parentBeanFactory = createParentBeanFactory();
        beanFactory.setParentBeanFactory(parentBeanFactory);
        System.out.println("当前 BeanFactory的 ParentFactory ：" + beanFactory.getParentBeanFactory());
        displayContainBean(beanFactory, "user");
        displayContainBean(parentBeanFactory, "user");
        applicationContext.refresh();
        applicationContext.close();
    }

    private static void displayContainBean(HierarchicalBeanFactory beanFactory, String beanName) {
        System.out.printf("当前BeanFactory[%s]是否包含bean[name:%s]:%s%n", beanFactory, beanName, containBean(beanFactory, beanName));
    }

    private static boolean containBean(HierarchicalBeanFactory beanFactory, String beanName) {
        BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();
        if (parentBeanFactory instanceof HierarchicalBeanFactory) {
            return containBean((HierarchicalBeanFactory) parentBeanFactory, beanName);
        }
        return beanFactory.containsBean(beanName);
    }

    private static ConfigurableListableBeanFactory createParentBeanFactory() {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
        String location = "classpath:/META-INF/dependency-lookup-context.xml";
        beanDefinitionReader.loadBeanDefinitions(location);
        return beanFactory;
    }

    {
        str = "attach 附加  attach ignore ignore ignore  ";
    }
}
